package com.konsung.ksdc.manager.community;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.netbean.ContactRequestNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.KsdcMqttClient;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.service.MqttService;

import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 创建者     kgh
 * 创建时间   2016/6/14 18:29
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述  联系人申请界面
 */
public class ContactRequestActivity extends Activity {
    @Bind(R.id.lv_contact_request)
    ListView lvContactRequest;
    @Bind(R.id.iv_back)
    ImageView ivBack;

    private List<ContactRequestNetBean> contactRequests;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            ContactRequestListAdapter adapter = new ContactRequestListAdapter(contactRequests,
                    ContactRequestActivity.this);
            lvContactRequest.setAdapter(adapter);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_request);
        ButterKnife.bind(this);

        loadContactRequests();

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        registerReceiver();
    }

    /**
     * 注册网络断开广播
     */
    private void registerReceiver() {
        IntentFilter intent = new IntentFilter();
        intent.addAction(BroadCastActions.ACTION_REQUEST_RECEIVED);
        intent.addAction(BroadCastActions.ACTION_REQUEST_PASSED);
        registerReceiver(receiver, intent);
    }

    /**
     * 广播接收者
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            if (BroadCastActions.ACTION_REQUEST_RECEIVED.equals(intent.getAction())) {
                loadContactRequests();
            }
            if (BroadCastActions.ACTION_REQUEST_PASSED.equals(intent.getAction())) {
                loadContactRequests();
            }

        }
    };

    /**
     * 加载好友申请信息
     */
    public void loadContactRequests() {

        RequestUtils.findRequestByUserId(NetConfig.currentUser.getUserId(), new RequestCallback() {

            @Override
            public void onError(Call call, Exception e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();

                if (Constants.REQUEST_OK.equals(resultCode)) {
                    contactRequests = responseBean.getList(new
                            TypeToken<List<ContactRequestNetBean>>() {
                            }.getType());
                    handler.sendEmptyMessage(1);
                }
            }
        });

        lvContactRequest.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ContactRequestNetBean bean = contactRequests.get(position);

                RegisterUserNetBean user = bean.getRequestUser();
                String userId = NetConfig.currentUser.getUserId();
                if (userId.equals(bean.getRequestUser().getUserId())) {
                    user = bean.getTargetUser();
                }

                Intent intent = new Intent(ContactRequestActivity.this,
                        ContactIndexActivity.class);

                Gson gson = new Gson();
                intent.putExtra("data", gson.toJson(user));
                startActivity(intent);
            }
        });
    }

    /**
     * 初始化联系人列表
     * @param contactBean 数据
     * @throws Exception 异常
     */
    public void saveContactToDb(RegisterUserNetBean contactBean) throws Exception {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(this).getRuntimeExceptionDao(
                RegisterUserNetBean.class);
        QueryBuilder qb = dao.queryBuilder();
        qb.where().eq("userId", contactBean.getUserId()).and()
                .eq("ownerId", NetConfig.currentUser.getUserId());

        List<RegisterUserNetBean> contact = dao.query(qb.prepare());
        if (!contact.isEmpty()) {
            return;
        }
        contactBean.setOwnerId(NetConfig.currentUser.getUserId());
        dao.create(contactBean);
    }

    /**
     * 发送图片
     * @param userName 用户
     * @throws Exception 异常
     */
    public void sendMessage(String userName) throws Exception {
        KsdcMqttClient client = MqttService.mqttClient;
        if (client == null || !client.isConnected()) {
            throw new Exception();
        }

        String msgSendDate = DateUtils.getStringDateFormat(new Date(), DateUtils.yyyyMMddHHmmss);
        String targetType = MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL;

        MqttMsgBean bean = new MqttMsgBean();
        bean.setMsgContent("");
        bean.setMsgSendDate(msgSendDate);
        bean.setMsgTargetType(targetType);
        bean.setMsgType(MqttMsgUtils.MSG_TYPE_REQUEST_PASSED);
        bean.setContact(NetConfig.currentUser.getUserId());
        bean.setTopicName(userName);

        byte[] msgContent = MqttMsgUtils.msgBeanParseByte(bean);
        client.publish(bean.getTopicName(), msgContent, 2, false);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadContactRequests();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }
}
